package controller;

import action.UserInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import result.CodeMsg;
import result.Result;
import service.impl.UserServiceImpl;
import java.util.Map;

@Before(UserInterceptor.class)
public class UserController extends Controller {
    UserServiceImpl userService= UserServiceImpl.userService;

    public void userManage(){
        render("/user/userManage.html");
    }
    public void listUser(){
       Integer limit= getParaToInt("limit");
       Integer page = getParaToInt("page");
       Map<String,Object> map= userService.listUsers(page,limit);
       renderJson(Result.layui((Long) map.get("count"),map.get("list")));
    }

    public void updateUser(){
       Integer id= getParaToInt("id");
       String username=getPara("username");
       String password = getPara("password");
       String userType = getPara("userType");
       Record record =  new Record();
       record.set("id",id);
       record.set("username",username);
       record.set("password",password);
       record.set("user_type",userType);
       boolean result=userService.updateUser(record);
       renderJson(result?Result.success(CodeMsg.SUCCESS):Result.error(CodeMsg.UPDATE_USER_ERROR));
    }

    public  void  addUser(){
        String username=getPara("username");
        if (userService.nameExisted(username)){
            renderJson(Result.error(CodeMsg.USERNAME_EXISTED));
        }else {
            String password = getPara("password");
            String userType = getPara("userType");
            Record record = new Record();
            record.set("username", username);
            record.set("password", password);
            record.set("user_type", userType);
            boolean result = userService.addUser(record);
            renderJson(result ? Result.success(CodeMsg.SUCCESS) : Result.error(CodeMsg.ADD_USER_ERROR));
        }
    }
    public  void  removeUsers(){
        String[] ids=getParaValues("id[]");
        String userType=getPara("userType");
        String length=getPara("length");
        Integer size=userService.removeUsers(ids);
        renderJson(size > 0?Result.success(CodeMsg.SUCCESS):Result.error(CodeMsg.REMOVE_USERS_ERROR));
    }

}
